import wtforms
from wtforms.validators import *
from flask import *
from exts import *
from models import *
from werkzeug.security import check_password_hash
from flask import session


#注册注册表单检查 
class RegisterForm(wtforms.Form):
    username = wtforms.StringField(validators=[Length(min=1, max=20, message='用户名长度在1-20个字符之间')])
    email = wtforms.StringField(validators=[Email(message='邮箱格式不正确')])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message='密码长度在6-20个字符之间')])
    password_confirm = wtforms.StringField(validators=[EqualTo('password', message='两次密码不一致')])

    # 自定义验证器

    # 验证邮箱是否已存在
    def validate_email(self, field):
        email = field.data
        user = User.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message='邮箱已存在')

# 登录表单检查
class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message='邮箱格式不正确')])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message='密码长度在6-20个字符之间')])

    def validate_email(self,field):
        email = field.data
        password = self.password.data        
        user = User.query.filter_by(email=email).first()
        
        if not user:
            raise wtforms.ValidationError(message='邮箱不存在')
        
        if user.password_hash != hashlib.md5(password.encode('utf-8')).hexdigest():
            raise wtforms.ValidationError(message='密码不正确')

# 对发送的tiezi进行检查
class PostTieziForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=1, max=500, message='内容长度在1-500个字符之间')])
    title = wtforms.StringField(validators=[Length(min=1, max=250, message='标题长度在1-250个字符之间')])
    user_id = wtforms.IntegerField(validators=[InputRequired(message='用户id必须填写')])

    def validate_user_id(self,field):
        user_id = field.data
        user = User.query.get(user_id)
        if not user:
            raise wtforms.ValidationError(message='用户不存在')


# 对teizi进行回复的Reply表单进行检查
class PostReplyForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=1, max=500, message='内容长度在1-500个字符之间')])
    user_id = wtforms.IntegerField(validators=[InputRequired(message='用户id必须填写')])
    post_id = wtforms.IntegerField(validators=[InputRequired(message='帖子id必须填写')])

    def validate_post_id(self,field):
        post_id = field.data
        tiezi_id = Tiezi.query.get(post_id)
        if not tiezi_id:
            raise wtforms.ValidationError(message='帖子不存在')
    def validate_user_id(self,field):
        user_id = field.data
        user = User.query.get(user_id)
        if not user:
            raise wtforms.ValidationError(message='用户不存在')
        

class PostLikeTieziForm(wtforms.Form):
    user_id = wtforms.IntegerField(validators=[InputRequired(message='用户id必须填写')])
    post_id = wtforms.IntegerField(validators=[InputRequired(message='帖子id必须填写')])
    def validate_post_id(self,field):
        post_id = field.data
        tiezi_id = Tiezi.query.get(post_id)
        if not tiezi_id:
            raise wtforms.ValidationError(message='帖子不存在')

class PostLikeReplyForm(wtforms.Form):
    user_id = wtforms.IntegerField(validators=[InputRequired(message='用户id必须填写')])
    reply_id = wtforms.IntegerField(validators=[InputRequired(message='回复id必须填写')])

    def validate_reply_id(self,field):
        reply_id = field.data
        reply_id = Reply.query.get(reply_id)
        if not reply_id:
            raise wtforms.ValidationError(message='回复不存在')


class PostLoginAdminForm(wtforms.Form):
    username = wtforms.StringField(validators=[Length(min=1, max=20, message='用户名长度在1-20个字符之间')])
    password = wtforms.StringField(validators=[Length(min=5, max=20, message='密码长度在5-20个字符之间')])

    def validate_username(self, field):
        username = field.data
        password = self.password.data
        admin_user = AdminUser.query.filter_by(username=username).first()
        import hashlib
        if not admin_user or admin_user.password_hash != hashlib.md5(password.encode('utf-8')).hexdigest():
            raise wtforms.ValidationError(message='用户名或密码不正确')
            
        

class ArticleForm(wtforms.Form):
    title = wtforms.StringField('Title', [
        DataRequired(message="标题不能为空"),
        Length(min=1, max=100, message="标题长度必须在1到100个字符之间")
    ])
    view_date = wtforms.DateTimeField('View Date', [
        DataRequired(message="发布日期不能为空")
    ], format='%Y-%m-%d %H:%M:%S', default=lambda: datetime.now())
    contents_json = wtforms.StringField('Contents JSON', [
        DataRequired(message="内容不能为空")
    ])
    column = wtforms.StringField('Column', [
        DataRequired(message="栏目不能为空"),
        Length(min=1, max=50, message="栏目长度必须在1到50个字符之间")
    ])

class PetForm(wtforms.Form):
    print('petform',wtforms.Form)
    全名 = wtforms.StringField(validators=[
        InputRequired(message='全名必须填写'),
        Length(min=1, max=255, message='全名长度在1-255个字符之间')
    ])
    别名 = wtforms.StringField(validators=[Length(min=0, max=255, message='别名长度在0-255个字符之间')])
    分类 = wtforms.StringField(validators=[Length(min=0, max=255, message='分类长度在0-255个字符之间')])
    体型 = wtforms.StringField(validators=[Length(min=0, max=255, message='体型长度在0-255个字符之间')])
    毛发 = wtforms.StringField(validators=[Length(min=0, max=255, message='毛发长度在0-255个字符之间')])
    智商 = wtforms.StringField(validators=[Length(min=0, max=255, message='智商长度在0-255个字符之间')])
    寿命 = wtforms.StringField(validators=[Length(min=0, max=255, message='寿命长度在0-255个字符之间')])
    饲养 = wtforms.StringField(validators=[Length(min=0, max=255, message='饲养长度在0-255个字符之间')])
    功能 = wtforms.StringField(validators=[Length(min=0, max=255, message='功能长度在0-255个字符之间')])
    原产地 = wtforms.StringField(validators=[Length(min=0, max=255, message='原产地长度在0-255个字符之间')])
    价格 = wtforms.StringField(validators=[Length(min=0, max=255, message='价格长度在0-255个字符之间')])
    imgPath = wtforms.StringField(validators=[Length(min=0, max=255, message='图片路径长度在0-255个字符之间')])
    简介 = wtforms.StringField(validators=[
        InputRequired(message='简介必须填写'),
        Length(min=1, max=1000, message='简介长度在1-1000个字符之间')
    ])



class UserForm(wtforms.Form):
    username = wtforms.StringField(validators=[
        InputRequired(message='用户名必须填写'),
        Length(min=1, max=20, message='用户名长度在1-20个字符之间')
    ])
    email = wtforms.StringField(validators=[
        InputRequired(message='邮箱必须填写'),
        Email(message='邮箱格式不正确')
    ])
    password = wtforms.StringField(validators=[
        InputRequired(message='密码必须填写'),
        Length(min=6, max=20, message='密码长度在6-20个字符之间')
    ])

    # 验证邮箱是否已存在（添加用户时使用）
    def validate_email(self, field):
        email = field.data
        user = User.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message='邮箱已存在')

class UserUpdateForm(wtforms.Form):
    username = wtforms.StringField(validators=[
        InputRequired(message='用户名必须填写'),
        Length(min=1, max=20, message='用户名长度在1-20个字符之间')
    ])
    email = wtforms.StringField(validators=[
        InputRequired(message='邮箱必须填写'),
        Email(message='邮箱格式不正确')
    ])
    password = wtforms.StringField(validators=[
        Length(min=0, max=20, message='密码长度在0-20个字符之间')
    ])
    
    # 验证邮箱是否已存在（更新用户时使用）
    def validate_email(self, field):
        email = field.data
        user_id = self.user_id.data if hasattr(self, 'user_id') else None
        
        # 查询是否有其他用户使用了这个邮箱
        query = User.query.filter_by(email=email)
        if user_id:
            query = query.filter(User.id != user_id)
            
        existing_user = query.first()
        if existing_user:
            raise wtforms.ValidationError(message='邮箱已被其他用户使用')





class TieziUpdateForm(wtforms.Form):
    title = wtforms.StringField(validators=[
        InputRequired(message='标题必须填写'),
        Length(min=1, max=100, message='标题长度在1-100个字符之间')
    ])
    content = wtforms.StringField(validators=[
        InputRequired(message='内容必须填写'),
        Length(min=1, max=1000, message='内容长度在1-1000个字符之间')
    ])